(function (window) {
    var JoinActivity = function () {
        /*var pattern = /(.+)-activity.changyou.com/;
        var match = window.location.host.match(pattern);
        if (undefined == match || null == match) return;
        // 兼容indexOf();
        if (!Array.prototype.indexOf)  Array.prototype.indexOf = (function(Object, max, min){
            "use strict";
            return function indexOf(member, fromIndex) {
                if(this===null||this===undefined)throw TypeError("Array.prototype.indexOf called on null or undefined");

                var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len);
                if (i < 0) i = max(0, Len+i); else if (i >= Len) return -1;

                if(member===void 0){ for(; i !== Len; ++i) if(that[i]===void 0 && i in that) return i; // undefined
                }else if(member !== member){   for(; i !== Len; ++i) if(that[i] !== that[i]) return i; // NaN
                }else                           for(; i !== Len; ++i) if(that[i] === member) return i; // all else

                return -1; // if the value was not found, then return -1
            };
        })(Object, Math.max, Math.min);
        // window.document.domain;
        var _host = match[1];
        // if(!pattern.test(window.location.host)) return;
        // _host = window.location.host.substring(0, window.location.host.lastIndexOf('-'));
        var domains = ['join', 'pre', 'pre-join', 'test', 'test-join', 'local', 'local-join'];
        if (domains.indexOf(_host) != -1) {
            _host = "http://" + _host + "-activity.changyou.com";
        } else _host = "http://join-activity.changyou.com";*/

        var curWwwPath = window.document.location.href;
        //获取主机地址之后的目录，如： /ems/Pages/Basic/Person.jsp
        var pathName = window.document.location.pathname;
        var pos = curWwwPath.indexOf(pathName);
        //获取主机地址，如： http://localhost:8080
        var _host = curWwwPath.substring(0, pos);
        var _host2 = _host.substring(_host.lastIndexOf("//")+2);
        var _isOut = false;
        var permit = ["xtlactivity.changyou.com", "tlsp.changyou.com","ldjsy-activity.changyou.com","tlus.changyou.com","tlnsh.changyou.com","tlim.changyou.com","tlurg.changyou.com","tlh5.changyou.com"];
       if (_host.indexOf('activity.changyou.com') == -1 && _host.indexOf('activity.cyou-inc.com') == -1 && permit.indexOf(_host2) == -1) {
            _host = '//join-activity.changyou.com';
            _isOut = true;
        }
        this.options = {
            host: _host,
            isOut: _isOut,
            notAutoAuthLogin: 0,//默认开启自动auth登陆
            key: {
                token: "JOIN_TOKEN",
                app: "APP",
                activity: "ACTIVITY",
                version: "VERSION",
                client: "CLIENT",
                cyscid: "CYSCID"
            },
            ready: function () {
            }
        };
    };
    JoinActivity.fn = JoinActivity.prototype = {
        simpleConfig: function (app, activity, version, platform, readyFunc, loginBackFunc, notAutoAuthLogin) {
            this.config({
                app: app,
                activity: activity,
                version: version,
                platform: platform,
                ready: readyFunc,
                loginBack: loginBackFunc,
                notAutoAuthLogin: notAutoAuthLogin
            });
        },
        config: function (options) {
            if (options == undefined) {
                options = {};
            }
            this.options = $.extend({}, this.options, options);
            if (this.options.platform == undefined) {//只有landing需要该参数
                alert("未设置登录平台");
            }
            if (this.options.app == undefined || this.options.activity == undefined || this.options.version == undefined) {
                alert("未设置SDK的活动标识");
            }
            if (this.options.notAutoAuthLogin == undefined) {//是否关闭plat=changyou时1012状态码的自动跳转auth登陆
                this.options.notAutoAuthLogin = 0;//默认开启自动auth登陆
            }
            localStorage.setItem(ja.options.key.app, this.options.app);
            localStorage.setItem(ja.options.key.activity, this.options.activity);
            localStorage.setItem(ja.options.key.version, this.options.version);

            var cyscid = ja.getParam(ja.options.key.cyscid);
            if (cyscid != undefined && null != cyscid && "" != cyscid && "null" != cyscid) {
                localStorage.setItem(ja.options.key.cyscid, cyscid);
            }

            // 登录异常判断
            var jcode = ja.getQueryString('jcode');
            if(jcode) {
                var errMsg = '';
                var paramsObj = ja.getParams(location.href);
                var paramsStr = '';
                var origin = location.origin || location.protocol + '//' + location.host;
                switch (Number(jcode)) {
                    case 1001: errMsg = '登录异常'; break;
                    case 1007: errMsg = '网络繁忙'; break;
                    case 1300: errMsg = '畅游登录异常'; break;
                    case 3103: errMsg = '您的账号已封停'; break;
                    default: errMsg = '登录异常';
                }
                alert(errMsg);
                delete paramsObj.jcode;
                if(Object.keys(paramsObj).length > 0) paramsStr = '?' + $.param(paramsObj);
                location.href = origin + location.pathname + paramsStr;
            }

            // 初始化接口请求
            var api = "/" + this.options.platform + "/landing/init";
            this.ajax(api, function (data) {
                if (data.code == 0) document.location.reload();
                if (data.code != 10000) {
                    sessionStorage.setItem('activity-active-code', data.message);
                    alert(data.message);
                    ja.options.ready();
                    return;
                } else {
                    sessionStorage.removeItem('activity-active-code');
                }
                ja.app = data.data.app;
                ja.activity = data.data.activity;
                ja.token = data.data.token;
                ja.client = data.data.client;
                if (window.localStorage) {
                    localStorage.setItem(ja.options.key.token, data.data.token);
                    localStorage.setItem(ja.options.key.app, data.data.activity.appCode);
                    localStorage.setItem(ja.options.key.activity, data.data.activity.activityCode);
                    localStorage.setItem(ja.options.key.version, data.data.activity.activityVersion);
                    localStorage.setItem(ja.options.key.client, data.data.client);
                }

                if (ja.options.platform == 'wechat') {
                    ja.slogin(1);
                    $.getScript("https://res.wx.qq.com/open/js/jweixin-1.2.0.js", function () {
                        $.getScript(ja.options.host + "/js/join-activity-wechat-1.0.0.js", function () {
                            ja.options.ready();
                        });
                    });
                } else {
                    if (data.data.activity.openWx > 0) {
                        $.getScript("https://res.wx.qq.com/open/js/jweixin-1.2.0.js", function () {
                            $.getScript(ja.options.host + "/js/join-activity-wechat-1.0.0.js", function () {
                                ja.options.ready();
                            });
                        });
                    } else {
                        ja.options.ready();
                    }
                    ja.slogin(0);
                }
            });
        },
        getQueryString: function(name) {
            var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if(r != null) return  r[2]; return null;
        },
        getParams: function(url) {
            var url = url || location.href; //获取url中"?"符后的字串
            var theRequest = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.split('?')[1];
                var strs = str.split("&");
                for(var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
                }
            }
            return theRequest;
        },
        getParam: function (paramKey) {
            var result = window.location.search.match(new RegExp("[\?\&]" + paramKey + "=([^\&]+)", "i"));
            if (result == null || result.length < 1) {
                return "";
            }
            return result[1];
        },
        getCyscid: function () {
            var cyscid = localStorage.getItem(ja.options.key.cyscid);
            if (!cyscid || "null" == cyscid) {
                cyscid = "";
            }
            return cyscid;
        },
        configDomain: function (domain) {
            if (undefined == domain || null == domain || '' == domain) return;
            this.options.host = domain;
        },
        getDomain: function () {
            if (undefined == this.options) {
                console.error("option undefined");
            }// return "http://join-activity.changyou.com";
            return this.options.host;
        },
        isOut: function () {
            return this.options.isOut;
        },
        ajax: function (api, data, fn) {
            var ajaxOptions = {
                success: function () {
                }
            };
            if (typeof api == "string") {
                ajaxOptions.api = api;
                if ($.isFunction(data)) {
                    ajaxOptions.success = data;
                } else if (data != undefined) {
                    ajaxOptions.data = data;
                }
                if ($.isFunction(fn)) {
                    ajaxOptions.success = fn;
                }
            } else if (typeof api == "object") {
                ajaxOptions = $.extend(ajaxOptions, api);
            }

            var _host;
            if (undefined == this.options) {
                console.error("option undefined");
            }
            /*_host = "http://join-activity.changyou.com";
            else */
            _host = this.options.host;
            var _options = $.extend({
                url: _host + ajaxOptions.api,
                //contentType: "application/json",
                headers: {
                    "Authorization": ja.user.getToken(),
                    "APP": ja.options.app,
                    "ACTIVITY": ja.options.activity,
                    "VERSIONCODE": ja.options.version,
                    "CYSCID": ja.getCyscid(),
                },
                cache: false,
                dataType: "json",
                xhrFields: {withCredentials: true}
            }, ajaxOptions, {
                success: function (data, textStatus, jqXHR) {
                    if (data && data.code && (data.code == 1012 || data.code == 1019)) {
                        if (ja.options.notAutoAuthLogin == 1 && (data.code == 1012 || data.code == 1019) && (ja.options.platform == 'phone' || ja.options.platform == 'changyou' || data.plat == 'changyou' )) {
                            //不自动登录
                        } else {
                        	if(data.plat!=undefined && data.plat!=''){
                        		ja.login(data.plat);
                        	}else{
                        		ja.login(ja.options.platform);
                        	}
                            return;
                        }
                    }
                    if (data && data.refreshToken && data.refreshToken == 1) {
                        //console.info('before--'+ja.token);
                        ja.token = ja.utils.readCookie('JOIN_TOKEN');
                        //console.info('after--'+ja.token);
                    }
                    ajaxOptions.success(data, textStatus, jqXHR);
                }
            });
            $.ajax(_options);
        },
        getActivity: function () {
            return this.activity;
        },
        getClient: function () {
            return this.client;
        },
        getApp: function () {
            return this.app;
        },
        getPlatform: function () {
            return this.options.platform;
        },
        getLanding: function () {
            return this.options.host + "/" + this.options.platform + "/landing";
        },
        logout: function () {
            this.ajax({
                type: 'post',
                url: this.options.host + "/" + this.options.platform + "/core/login/" + this.options.app + "/" + this.options.activity + "/" + this.options.version + "/logout",
                success: function () {
                    if (ja.options.platform == 'changyou' || ja.options.platform == 'warframe'|| ja.options.platform == 'changyouwg') {
                    	var gtc= ja.utils.readCookie("CASGTC");
                    	ja.utils.setCookie('CASGTC', '', 0);
                        var currURL = location.href;
                        if(currURL.indexOf("#") != -1){
                            currURL = currURL.split("#")[0];
                        }
                        location.href = "https://auth.changyou.com/logout.jsp?b=" + currURL +"&co="+gtc;
                    } else if(ja.options.platform == 'wechat'){
                    	ja.utils.setCookie('CASGTC', '', 0);
                    	var locationUrl = window.location.href;
                        location.href = "https://auth.changyou.com/logout.jsp?b=" + locationUrl
                    }else {
                    	var locationUrl = window.location.href;
                    	location.href = locationUrl.indexOf('?')==-1 ? locationUrl+"?v="+10000*Math.random() : locationUrl+"&v="+10000*Math.random();
                    }
                }
            });
        },
        slogin: function (must) {
            ja.login(ja.getPlatform(), must)
        },
        login: function (platform, must, back) {
            var activeCode = sessionStorage.getItem('activity-active-code');
            if (activeCode != undefined) {
                alert(activeCode);
                return;
            }
            if (must == undefined) {
                must = 1;
            }
            if (back == undefined) {
                back = window.location.href;
            }
            var _app = ja.options.app;
            var _act = ja.options.activity;
            var _ver = ja.options.version;
            var url = this.options.host + "/" + platform + "/core/login/" + _app + "/" + _act + "/" + _ver + "?callback=" + encodeURI(back);
            var platformLogin = {
                wechat: function () {
                    if (ja.client.isWechat) {
                        window.location.href = url;
                    }
                },
                cyou: function () {
                	$('#login_content').show();
                },
                cyou3: function () {
                    if (ja.client.isMobile) {
                        window.location.href = url;
                    } else {
                        ja.utils.win.open(490, 470, url);
                    }
                },
                changyou: function () {
                    if (ja.client && ja.client.isForceMobileLogin) {
                        console.log("force mobile login");
                        if (ja.client.isMobile) {
                            ja.utils.win.open(490, 720, url);
                        } else {
                            ja.utils.win.open(320, 550, url);
                        }
                    } else if (ja.client && ja.client.isMobile) {
                        console.log("changyou平台手机端登录");
                        window.location.href = url;
                    } else {
                        console.log("changyou平台PC端登录");
                        ja.utils.win.open(490, 352, url);
                    }
                },
                warframe: function () {
                    if (ja.client.isMobile) {
                        window.location.href = url;
                    } else {
                        ja.utils.win.open(490, 352, url);
                    }
                },
                changyouwg: function () {
                    if (ja.client.isMobile) {
                        window.location.href = url;
                    } else {
                        ja.utils.win.open(500, 360, url);
                    }
                },
                dj: function () {
                    djLogin();
                }
            };

            this.ajax({
                url: this.options.host + "/" + platform + "/user/info",
                success: function (data) {
                    if (data.code != 10000) {
                        if (must == 1) {
                            platformLogin[platform]();
                        }
                    } else {
                        if (ja.options.loginBack) {
                            ja.options.loginBack(data);
                        }
                    }
                },
                error: function () {
                    platformLogin[platform]();
                }
            });

        },
        user: {
            getToken: function () {
                return ja.token;
            },
            getWx: function (success) {
                this.get("wechat", success);
            },
            get: function (platform, success,must) {
            	if (must == undefined) {
                    must = 1;
                }
                ja.ajax({
                    url: ja.options.host + "/" + platform + "/user/info",
                    error: function () {
                        ja.login(platform,must);
                    },
                    success: function (data) {
                        if (data.code != 10000) {
                            ja.login(platform,must);
                            return;
                        }
                        success(data);
                    }
                });
            }
        },
        utils: {
            win: {
                scrolling: 'no',
                //是否显示滚动条 no,yes,auto
                int: function () {
                    $("#winClose").on('mouseenter',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('mouseleave',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('click',
                        function () {
                            $("#mask,#maskTop").fadeOut(function () {
                                $(this).remove();
                            });
                        });
                },
                open: function (width, height, src) {
                    var iframeHeight = height;
                    var marginLeft = width / 2;
                    var marginTop = height / 2;
                    var inntHtml = '';
                    inntHtml += '<div id="mask" style="width:100%; height:100%; position:fixed; top:0; left:0; z-index:1999;background:#cccccc; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity:0.5;"></div>';
                    inntHtml += '<div id="maskTop" style="width: ' + width + 'px; height: ' + height + 'px;  color: #333; position: fixed; top: 50%; left: 50%; margin-left: -' + marginLeft + 'px; margin-top: -' + marginTop + 'px; z-index: 2999; ">';
                    inntHtml += '<div id="maskTitle" style="height: 0px;position: relative;">';
                    inntHtml += '<div id="winClose" style="width: 28px; height: 28px; cursor: pointer; position: absolute; top: -12px; right: -9px; background-image: url();"></div>';
                    inntHtml += '</div>';
                    inntHtml += '<iframe width="' + width + '" height="' + iframeHeight + '" frameborder="0" scrolling="' + this.scrolling + '" src="' + src + '"></iframe>';
                    inntHtml += '</div>';
                    $("body").append(inntHtml);
                    this.int();
                },
                close: function () {
                    $("#winClose").click();
                }
            }
            , readCookie: function (name) {
                var cookieValue = "";
                var search = name + "=";
                if (document.cookie.length > 0) {
                    offset = document.cookie.indexOf(search);
                    if (offset != -1) {
                        offset += search.length;
                        end = document.cookie.indexOf(";", offset);
                        if (end == -1)
                            end = document.cookie.length;
                        cookieValue = unescape(document.cookie.substring(offset, end))
                    }
                }
                return cookieValue;
            },
            setCookie :function(b, c, a) {
                var d = new Date();
                d.setDate(d.getDate() + a);
                document.cookie = b + "=" + escape(c) + ((a == null) ? "": "; expires=" + d.toGMTString()) + "; path=/; domain=changyou.com";
            }
        }
    };
    window.ja = new JoinActivity();
}(window));
